var fs = require("fs");
var path = require("path");


var mslibrary = require('ms-common-library');

var openfile = mslibrary.openfile;

module.exports = function (UC, source, config, ArFor, cache, package) {

    var editimage = config.EditImage;

    var size = config.ImageSize;

    var ImagelocalPath = config.ImagelocalPath;

    var packageFile = package.dirname;
    var svgs = {
        error: {
            file: path.join(packageFile, "./static/error.svg"),
            Size: {
                height: 6090,
                width: 7060
            }
        },
        error_2: {
            file: path.join(packageFile, "./static/error_2.svg"),
            Size: {
                height: 5400,
                width: 6000
            }
        },
        warning: {
            file: path.join(packageFile, "./static/error.svg"),
            Size: {
                height: 5400,
                width: 6100
            }
        },
        video: {
            file: path.join(packageFile, "./static/video.svg"),
            Size: {
                height: 4000,
                width: 2400
            }
        }
    }
    var OutputPictures = function (res, params, error) {
        var imgfile = params.imgfile;
        if (imgfile == null) {
            var key = "error";
            if (error && error.name) {
                if (svgs[error.name]) {
                    key = error.name;
                }
            }
            var svg = svgs[key];

            var sendsvg = function (val) {
                var _size = size(params, svg.Size);
                val = val.replace("{{width}}", _size.width);
                val = val.replace("{{height}}", _size.height);

                console.log('error')

                res.type('svg');

                var etag = 'W/ms-' + mslibrary.MD5(key)
                res.setHeader('Etag', etag);
                res.setHeader('Cache-Control', "max-age=" + (60 * 60 * 24 * 30));
                res.status(200).send(val);

            }
            if (svg.val) {
                sendsvg(svg.val)
            } else {
                var imgfile = svg.file;
                openfile(imgfile, function (error, svgimg) {
                    svg.val = svgimg;
                    sendsvg(svgimg)
                })
            }
        } else {

            fs.exists(imgfile, function (exists) {
                //  res.type('application/x-png');
                if (exists) {
                    if (res.etag_key) {
                        res.setHeader('Etag', res.etag_key);
                    }
                    /* else if (res.last_modified) {

                                            res.setHeader('Last-Modified', res.last_modified);

                                        }*/


                    res.setHeader('Cache-Control', "max-age=" + (60 * 60 * 24 * 30));

                    ////  res.sendfile(imgfile);

                    imgfile=imgfile.Replace('\\','/');
                    var options = {
                        root: config.Files.Temp,
                        dotfiles: 'deny'
                    };
                    var fileName = imgfile.replace(config.Files.Temp, "");

                    // console.log(fileName);

                    res.sendFile(fileName, options, function (err) {
                        if (err) {
                            OutputPictures(res, {})
                        } else {
                            //console.log('Sent:', fileName);
                        }
                    });

                } else {
                    OutputPictures(res, {})
                }
            });
        }
    };

    config.OutputPictures = OutputPictures;

    var images = function (req, res, next) {

        var etag = config.getETag(req.path);
        if (req.isConditionalGET()) {

            var _etag = req.getHeader('if-none-match');
            if (_etag == etag) {
                req.notModified()
                return
            }
        };

        res.etag_key = etag;

        var params = req.params;

        var video2image = config.video2image;

        var renderimage = function (imgfile, error) {
            params.imgfile = imgfile;
            OutputPictures(res, params, error);
        }
        params.cache = config.Files.Temp;
        ImagelocalPath(params, function (error, localpath) {

            if (error == null) {

                renderimage(localpath);

            } else {
                new source({
                    "SQL": "SELECT db.src,db.FileType as type FROM files AS db WHERE db.id={id}",
                    "type": "row"
                }, {
                    id: params.id
                }, function (db) {
                    if (db && db.type == 6) {
                        var src = db.src;
                        var OriginalFile = path.join(config.Files.FileCache, src);

                        params.OriginalFile = OriginalFile;
                        video2image(params, function (error, db) {
                            if (error) {
                                renderimage(null, {
                                    name: "video"
                                })
                            } else {
                                params.OriginalFile = db.path;
                                if (process.FormName === 'electron') {
                                    params.nativeImage = config.nativeImage;
                                }
                                editimage(params, function (error, val) {
                                    if (error) {
                                        renderimage();
                                    } else {

                                        //var modified = new Date(Date.now() + 10 * 1000);

                                        //res.last_modified = modified.toUTCString();

                                        renderimage(val.path);
                                    }
                                })
                            }

                        })
                    } else if (db && db.src) {
                        var src = db.src;
                        var OriginalFile = path.join(config.Files.FileCache, src);
                        params.cache = config.Files.Temp;
                        params.OriginalFile = OriginalFile;
                        if (process.FormName === 'electron') {
                            params.nativeImage = config.nativeImage;
                        }
                        editimage(params, function (error, val) {
                            if (error) {
                                renderimage();
                            } else {

                                // var modified = new Date(Date.now() + 10 * 1000);

                                //   res.last_modified = modified.toUTCString();
                                renderimage(val.path);
                            }
                        })

                    } else {
                        renderimage()
                    }
                })
            }
        })


    };

    var router = function (req, res, next) {
        images(req, res, next)
    }
    return router;

}